package com.share.rabbitmq.message;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import com.share.rabbitmq.RabbitMQConnection;

/**
 * @desc:
 * @author:caifan
 * @date:2020/4/4
 */
public class MessageConsumer {
    public static void main(String[] args) throws Exception {
        Connection connect = RabbitMQConnection.connect();
        Channel channel = connect.createChannel();

//        String exchangeName = "share.directExchange";
//        String exchangeType = "direct";
//        String queueName = "share.directQueue";
//        String routingKey = "share.directExchange.key";
        String exchangeName = "my.directExchange";
        String exchangeType = "direct";
        String queueName = "my.directQueue";
        String routingKey = "my.directExchange.key";
        /**
         * 声明一个交换机
         * exchange:交换机的名称
         * type:交换机的类型 常见的有direct,fanout,topic等
         * durable:设置是否持久化。durable设置为true时表示持久化，反之非持久化.持久化可以将交换器存入磁盘，在服务器重启的时候不会丢失相关信息
         * autodelete:设置是否自动删除。autoDelete设置为true时，则表示自动删除。自动删除的前提是至少有一个队列或者交换器与这个交换器绑定，之后，所有与这个交换器绑定的队列或者交换器都与此解绑。
         * 不能错误的理解—当与此交换器连接的客户端都断开连接时，RabbitMq会自动删除本交换器
         * arguments:其它一些结构化的参数，比如：alternate-exchange
         */
        channel.exchangeDeclare(exchangeName,exchangeType,true,false,null);

        /**
         * 声明一个队列
         */
        channel.queueDeclare(queueName,true,false,false,null);

        /**
         * 队列和交换机绑定
         */
        channel.queueBind(queueName,exchangeName,routingKey);

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println("consumer message:" + message);
            System.out.println("consumerTag:" + consumerTag);
            System.out.println(delivery.getEnvelope() + "::" + delivery.getEnvelope().getDeliveryTag());
        };
        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {
            System.out.println(consumerTag);
        });

    }
}
